package com.szmg.wishwalls.dao.impl;

import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.szmg.wishwalls.dao.ProductionDao;
import com.szmg.wishwalls.model.Production;

@Repository("productionDao")
public class ProductionDaoImpl implements ProductionDao{
	@Resource(name="hibernateTemplate")
	private HibernateTemplate hibernateTemplate;
	
	public List<Production> queryProductionByProgramCode(String programCode){
		StringBuilder sb = new StringBuilder();
		sb.append("	FROM Production p");
		sb.append("	WHERE");
		sb.append("	EXISTS(");
		sb.append("		SELECT 1");
		sb.append("		FROM ProgramProductionRelation pr");
		sb.append("		WHERE pr.productionId = p.id");
		sb.append("		AND EXISTS(");
		sb.append("			SELECT 1");
		sb.append("			FROM Program pg");
		sb.append("			WHERE pg.code = ?");
		sb.append("			AND pg.id = pr.programId");
		sb.append("			AND curdate() BETWEEN pg.startDate and pg.endDate");
		sb.append("			)");
		sb.append("	)");
		List<Production> list = hibernateTemplate.find(sb.toString(),new Object[]{programCode});
		if(CollectionUtils.isEmpty(list)) return Collections.emptyList();
		return list;
	}
	
	public List<Production> queryProductionByMenuId(String programCode,String menuId){
		StringBuilder sb = new StringBuilder();
		sb.append("	FROM Production p");
		sb.append("	WHERE");
		sb.append("	EXISTS(");
		sb.append("		SELECT 1");
		sb.append("		FROM ProgramProductionRelation pr");
		sb.append("		WHERE pr.productionId = p.id");
		sb.append("		AND EXISTS(");
		sb.append("			SELECT 1");
		sb.append("			FROM Program pg");
		sb.append("			WHERE pg.code = ?");
		sb.append("			AND pg.id = pr.programId");
		sb.append("			AND curdate() BETWEEN pg.startDate and pg.endDate");
		sb.append("			)");
		sb.append("	)");
		sb.append("	and p.menuLeafId = ?");
		List<Production> list = hibernateTemplate.find(sb.toString(),new Object[]{programCode,menuId});
		if(CollectionUtils.isEmpty(list)) return Collections.emptyList();
		return list;
	}
	
	public List<Production> queryProductionByWishOrderId(String wishOrderId){
		StringBuilder sb = new StringBuilder();
		sb.append("	FROM Production p");
		sb.append("	WHERE");
		sb.append("	EXISTS(");
		sb.append("		SELECT 1");
		sb.append("		FROM OrderProductionRelation opr");
		sb.append("		WHERE opr.productionId = p.id");
		sb.append("		AND EXISTS(");
		sb.append("			SELECT 1");
		sb.append("			FROM WishOrder wo");
		sb.append("			WHERE opr.wishOrderId = wo.id");
		sb.append("			  and wo.id = ?");
		sb.append("			)");
		sb.append("	)");
		List<Production> list = hibernateTemplate.find(sb.toString(),new Object[]{wishOrderId});
		if(CollectionUtils.isEmpty(list)) return Collections.emptyList();
		return list;
	}

}
